//
//  UIImage+Extension.swift
//  GZWeibo009
//
//  Created by zhangping on 16/4/11.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

extension UIImage {
    /// 异步绘制图像
    func hm_asyncDrawImage(size: CGSize, bkgColor: UIColor? = UIColor.whiteColor(), isCorner: Bool = false, finished: (image: UIImage) -> ()) {
        
        dispatch_async(dispatch_get_global_queue(0, 0)) { () -> Void in
            let start = CACurrentMediaTime()
            
            // 如果指定了背景颜色，就不透明
            UIGraphicsBeginImageContextWithOptions(size, bkgColor != nil, UIScreen.mainScreen().scale)
            
            let rect = CGRect(origin: CGPointZero, size: size)
            
            // 设置填充颜色
            bkgColor?.setFill()
            UIRectFill(rect)
            
            // 设置圆角 - 使用路径裁切，注意：写设置裁切路径，再绘制图像
            if isCorner {
                let path = UIBezierPath(ovalInRect: rect)
                
                // 添加裁切路径 - 后续的绘制，都会被此路径裁切掉
                path.addClip()
            }
            
            // 绘制图像
            self.drawInRect(rect)
            
            let result = UIGraphicsGetImageFromCurrentImageContext()
            
            UIGraphicsEndImageContext()
            
            let end = CACurrentMediaTime()
//            print("消耗时间: \(end - start)")
            
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                finished(image: result)
            })
        }
    }
}
